package cn.com.connext.scrm.utils;
import cn.com.connext.scrm.utils.wdtutils.StringUtils;
import cn.hutool.core.codec.Base64;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;


import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

/**
 * @description: 带文字的二维码
 * @author: Ycc
 * @since: 2020/7/13
 **/
public class QRcodeUtils {

    public static BufferedImage generateQrCode(String content, String logoPath) {
        BufferedImage image = QrCodeUtil.generate(
            content, // 二维码内容
            QrConfig.create().setImg(logoPath)// 附带logo
                .setWidth(490) // 二维码的宽
                .setHeight(490) // 二维码的高
                .setMargin(0)); // 边距
        return image;
    }



    //区别于旧的方法
    public static BufferedImage createPictureNew(BufferedImage image, String bgPath, String text) {
        try {
            // 首先先画背景图片
            BufferedImage backgroundImage = ImageIO.read(new File(bgPath));
            // 背景图片的宽度
            int bgWidth = backgroundImage.getWidth();
            // 二维码的宽度
            int qrWidth = image.getWidth();
            // 二维码距离背景图片横坐标（X）的距离，居中显示
            int distanceX = (bgWidth - qrWidth) / 2;
            // 二维码距离背景图片纵坐标（Y）的距离
            int distanceY = distanceX;
            // 基于图片backgroundImage对象打开绘图
            Graphics2D rng = backgroundImage.createGraphics();
            rng.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP));
            rng.drawImage(image, distanceX, distanceY, null);

            //设置字体
            Font font = new Font("宋体", Font.PLAIN, 30);
            rng.setFont(font);
            rng.setColor(Color.black);
            // 获取当前文字的对象
            FontMetrics metrics = rng.getFontMetrics(font);

            // 文字在图片中的坐标 这里设置在中间
            int startX = (bgWidth - metrics.stringWidth(text)) / 2; //当前文字对象到横坐标（X）的距离
            int startY = backgroundImage.getHeight()-10; //当前文字对象到纵坐标（Y）的距离
            rng.drawString(text, startX, startY);
            // 处理绘图
            rng.dispose();
            image = backgroundImage;
            image.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将绘制好的图片返回
        return image;
    }
    public static String crateQRCode(String content, int width, int height) throws IOException {

        String resultImage = "";
        if (!StringUtils.isEmpty(content)) {
            ServletOutputStream stream = null;
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            @SuppressWarnings("rawtypes")
            HashMap<EncodeHintType, Comparable> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 指定字符编码为“utf-8”
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 指定二维码的纠错等级为中级
            hints.put(EncodeHintType.MARGIN, 2); // 设置图片的边距

            try {
                QRCodeWriter writer = new QRCodeWriter();
                BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

                BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
                ImageIO.write(bufferedImage, "png", os);
                /**
                 * 原生转码前面没有 data:image/png;base64 这些字段，返回给前端是无法被解析，可以让前端加，也可以在下面加上
                 */
                resultImage = new String("data:image/png;base64," + Base64.encode(os.toByteArray()));

                return resultImage;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (stream != null) {
                    stream.flush();
                    stream.close();
                }
            }
        }
        return null;
    }

}
